package com.maxatime.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.maxatime.Excel.ExcelReader;
import com.maxatime.Excel.ExcelWriter;
import com.maxatime.exception.PhoenixException;
import com.maxatime.pojo.*;
import com.maxatime.service.StudentMessageService;
import com.maxatime.utils.MyContent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author Mr.Zhao
 * @title: StudentMessageController
 * @projectName phoenix
 * @description: TODO
 * @date 2021/7/16 8:34
 */
@Controller
public class StudentMessageController {
    Logger log = LogManager.getLogger();

    @Autowired
    private StudentMessageService studentMessageService;


    /*
     *
     * @Author Mr.Zhao
     * @Title studentMess
     * @Description
     * @Date 9:02 2021/7/29
     * @Param [page, limit, studentName, mobile, sex, age, idNum]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @ResponseBody
    @RequestMapping("/studentMess")
    public Map<String, Object> studentMess(@RequestParam(required = false, defaultValue = "1") int page,
                                           @RequestParam(required = false, defaultValue = "7") int limit,
                                           String studentName, String mobile, String sex, Integer age, String idNum) {
        // 使用Pagehelper传入当前页数和页面显示条数会自动为我们的select语句加上limit查询
        // 从他的下一条sql开始分页
        PageHelper.startPage(page, limit);
        List<StudentMessage> stu = studentMessageService.studentMess(studentName, mobile, sex, age, idNum);// 这是我们的sql
        for (StudentMessage i : stu) {
            i.setNativePlace(i.getNativePlace());
        }

        log.info("data_______:::::" + stu);
        log.info("String studentName, String mobile, String sex,Integer age,String idNum：：：：：：："
                + studentName + "   "
                + mobile + "   "
                + sex + "   "
                + age + "   "
                + idNum + "   "
        );
        // 使用pageInfo包装查询
        PageInfo<StudentMessage> rolePageInfo = new PageInfo<>(stu);//
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", rolePageInfo.getTotal());
        map.put("data", rolePageInfo.getList());
        log.info("map------------------------------------" + map);
        return map;
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title studentDelete
     * @Description
     * @Date 9:01 2021/7/29
     * @Param [data]
     * @return java.lang.Integer
     **/
    @RequestMapping("/studentDelete")
    @ResponseBody
    public Integer studentDelete(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String student = jsonObject.getString("studentId");
        int studentId = Integer.parseInt(student);


        return studentMessageService.studentDelete(studentId);
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title updateView
     * @Description
     * @Date 9:01 2021/7/29
     * @Param [stu]
     * @return com.maxatime.pojo.StudentMessage
     **/
    @RequestMapping("/updateView")
    @ResponseBody
    public StudentMessage updateView(@RequestBody String stu) {

        JSONObject jsonObject = JSONObject.parseObject(stu);
//        String student = jsonObject.getString("studentId");
        int studentId = Integer.parseInt(jsonObject.getString("studentId"));
        log.info("ddddddddddddd" + studentId);
        return studentMessageService.updateView(studentId);
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title provinces
     * @Description
     * @Date 9:01 2021/7/29
     * @Param []
     * @return java.util.List<com.maxatime.pojo.Provinces>
     **/
    @ResponseBody
    @RequestMapping("/provinces")
    public List<Provinces> provinces() {
        return studentMessageService.provinces();
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title cities
     * @Description
     * @Date 9:01 2021/7/29
     * @Param []
     * @return java.util.List<com.maxatime.pojo.Cities>
     **/
    @ResponseBody
    @RequestMapping("/cities")
    public List<Cities> cities() {
        return studentMessageService.cities();
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title areas
     * @Description
     * @Date 9:01 2021/7/29
     * @Param []
     * @return java.util.List<com.maxatime.pojo.Areas>
     **/
    @ResponseBody
    @RequestMapping("/areas")
    public List<Areas> areas() {
        return studentMessageService.areas();
    }


    /*
     *
     * @Author Mr.Zhao
     * @Title student
     * @Description
     * @Date 9:02 2021/7/29
     * @Param []
     * @return java.lang.String
     **/
    @RequestMapping("/student")
    public String student() {
        return "/html/list";
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title updateStu
     * @Description
     * @Date 9:02 2021/7/29
     * @Param [updDate]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @ResponseBody
    @RequestMapping("/updateStu")
    public Map<String, Object> updateStu(@RequestBody String updDate) {

        Map<String, Object> m = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(updDate);
        StudentMessage stu = new StudentMessage();
        stu.setStudentId(Integer.parseInt(jsonObject.getString("studentId")));
        stu.setStudentName(jsonObject.getString("studentName"));
        stu.setMobile(jsonObject.getString("mobile"));
        stu.setSex(Integer.parseInt(jsonObject.getString("sex")));
        stu.setIdType(Integer.parseInt(jsonObject.getString("idType")));
        stu.setIdNum(jsonObject.getString("idNum"));
        stu.setBirthday(jsonObject.getDate("birthday"));
        stu.setProvincesId(Integer.parseInt(jsonObject.getString("provincesId")));
        stu.setCitiesId(Integer.parseInt(jsonObject.getString("citiesId")));
        stu.setAreasId(Integer.parseInt(jsonObject.getString("areasId")));
        stu.setDetailAddr(jsonObject.getString("detailAddr"));

        Calendar now = Calendar.getInstance();//获取时间
        stu.setUpdateDate(now.getTime());//当前时间
        try {

            Integer a = studentMessageService.updateStu(stu);
            m.put(MyContent.CODE, "0000");
            m.put(MyContent.MSG, "修改成功");
            m.put("data", a);

        } catch (PhoenixException e) {
            e.printStackTrace();
            log.error("exception:::" + e.getMessage());
            log.error("exception code:::" + e.getCode());
            log.error("exception msg:::" + e.getMsg());

            m.put(MyContent.CODE, e.getCode());
            m.put(MyContent.MSG, e.getMsg());
            m.put("data", 0);

        }
        return m;

    }



    /*
     *
     * @Author Mr.Zhao
     * @Title
     * @Description
     * @Date 9:02 2021/7/29
     * @Param
     * @return
     **/

    @ResponseBody
    @RequestMapping("/insertStu")
    public Map<String, Object> insertStu(@RequestBody String istDate) {

        Map<String, Object> m = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(istDate);
        StudentMessage stu = new StudentMessage();
        stu.setStudentNum(Integer.parseInt(jsonObject.getString("studentNum")));
        stu.setStudentName(jsonObject.getString("studentName"));
        stu.setMobile(jsonObject.getString("mobile"));
        stu.setSex(Integer.parseInt(jsonObject.getString("sex")));
        stu.setAge(Integer.parseInt(jsonObject.getString("age")));
        stu.setIdType(Integer.parseInt(jsonObject.getString("idType")));
        stu.setIdNum(jsonObject.getString("idNum"));
        stu.setBirthday(jsonObject.getDate("birthday"));
        stu.setProvincesId(Integer.parseInt(jsonObject.getString("provincesId")));
        stu.setCitiesId(Integer.parseInt(jsonObject.getString("citiesId")));
        stu.setAreasId(Integer.parseInt(jsonObject.getString("areasId")));
        stu.setDetailAddr(jsonObject.getString("detailAddr"));
        stu.setDeleteFlag(0);
        Calendar now = Calendar.getInstance();//获取时间
        stu.setCreateDate(now.getTime());
        stu.setUpdateDate(now.getTime());//当前时间

        try {
            Integer b = studentMessageService.insertStu(stu);
            m.put(MyContent.CODE, "0000");
            m.put(MyContent.MSG, "添加成功");
            m.put("data", b);
        } catch (PhoenixException e) {
            e.printStackTrace();
            log.error("exception::" + e.getMessage());
            log.error("exception:::code" + e.getCode());
            log.error("exception:::msg" + e.getMsg());
            m.put(MyContent.CODE, e.getCode());
            m.put(MyContent.MSG, e.getMsg());
            m.put("data", 0);

        }
        return m;


    }

    /*
     *
     * @Author Mr.Zhao
     * @Title deleteList
     * @Description
     * @Date 9:37 2021/7/29
     * @Param [jsonStr]
     * @return java.lang.Integer
     **/
    @ResponseBody
    @RequestMapping("/deleteList")
    public Integer deleteList(@RequestBody String jsonStr) {

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        JSONArray ids = jsonObject.getJSONArray("studentIds");
        Integer[] stuIds = new Integer[ids.size()];
        for (int i = 0; i < ids.size(); i++) {
            Object id = ids.get(i);
            stuIds[i] = Integer.parseInt(id.toString());
            log.info("id————————————" + Integer.parseInt(id.toString()));
        }
        List<Integer> list = Arrays.asList(stuIds);

        return studentMessageService.deleteList(list);
    }

    /*
     *
     * @Author Mr.Zhao
     * @Title classs
     * @Description
     * @Date 9:02 2021/7/29
     * @Param []
     * @return java.lang.String
     **/
    @RequestMapping("/class")
    public String classs() {
        return "/html/classlist";
    }


    @ResponseBody
    @RequestMapping("/studentMessdd")
    public Map<String, Object> studentMessdd(@RequestParam(required = false, defaultValue = "1") int page,
                                             @RequestParam(required = false, defaultValue = "7") int limit
    ) {
        // 使用Pagehelper传入当前页数和页面显示条数会自动为我们的select语句加上limit查询
        // 从他的下一条sql开始分页
        PageHelper.startPage(page, limit);
        List<StudentMessage> stu = studentMessageService.studentMessdd();// 这是我们的sql
        for (StudentMessage i : stu) {
            i.setNativePlace(i.getNativePlace());
        }

        // 使用pageInfo包装查询
        PageInfo<StudentMessage> rolePageInfo = new PageInfo<>(stu);//
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", rolePageInfo.getTotal());
        map.put("data", rolePageInfo.getList());
        log.info("map------------------------------------" + map);
        return map;
    }

    @RequestMapping("/import")
    public String importss(){

        String excelFileName = "D:\\guokai\\pho.xlsx";
        // 读取Excel文件内容
        List<StudentMessage> readResult = ExcelReader.readExcel(excelFileName);


        studentMessageService.inse(readResult);

        return "/html/list";
    }




    @RequestMapping("/export")
    public String export(String studentName, String mobile, String sex, Integer age, String idNum) {
        // 创建需要写入的数据列表
//        List<StudentMessage> dataVOList = new ArrayList<>(2);
        String exportFilePath = "D:\\guokai\\phoee.xlsx";
       List<StudentMessage> dataVOList =   studentMessageService.studentMess(studentName, mobile, sex, age, idNum);


        // 写入数据到工作簿对象内
        Workbook workbook = ExcelWriter.exportData(dataVOList);

        // 以文件的形式输出工作簿对象
        FileOutputStream fileOut = null;
        try {

            File exportFile = new File(exportFilePath);
            if (!exportFile.exists()) {
                exportFile.createNewFile();
            }

            fileOut = new FileOutputStream(exportFilePath);
            workbook.write(fileOut);
            fileOut.flush();
        } catch (Exception e) {
            log.info("输出Excel时发生错误，错误原因：" + e.getMessage());
        } finally {
            try {
                if (null != fileOut) {
                    fileOut.close();
                }
                if (null != workbook) {
                    workbook.close();
                }
            } catch (IOException e) {
                log.info("关闭输出流时发生错误，错误原因：" + e.getMessage());
            }
        }
        return "/html/list";

    }
//    @RequestMapping("/dddd")
//    public String dddd(){
//        return "/html/course";
//    }


      @RequestMapping("/wer")
      public String www(Model model){

          List<Exam> exams= studentMessageService.listss();


          model.addAttribute("exam",exams);

          for (int i = 0; i <exams.size(); i++) {



                  if (exams.get(i).getAge()-exams.get(i).getAge1()<=20){
                      exams.get(i).setLeancc("兄妹关系");
                  }else if (exams.get(i).getAge()-exams.get(i).getAge1()>20 && exams.get(i).getAge()-exams.get(i).getAge1()<=40){
                      exams.get(i).setLeancc("父子,母子");
                  }
                  else if (exams.get(i).getAge()-exams.get(i).getAge1()<=60 && exams.get(i).getAge()-exams.get(i).getAge1()>40){
                      exams.get(i).setLeancc("祖孙关系");
                  }
              }






        return "/html/exam";
      }







}
